<template>
  <div>
    <el-row :gutter="5">
      <el-col :span="5">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <div style="display: flex">
              <el-image :src="explain.iconUrl" style=" width: 35px;height: 35px;margin:3px;" />
              <div style="flex-grow: 1;margin-left: 13px;">
                <div>
                  <el-popover
                    v-if="explain.remark && explain.remark!==''"
                    placement="top"
                    width="200"
                    trigger="hover"
                    :content="explain.name"
                  >
                    <span slot="reference">{{ explain.remark }}</span>
                  </el-popover>
                  <span v-else>{{ explain.name }}</span>
                </div>
                <!--                <div style="margin-top: 2px">{{ $t('keyName') }}:{{ explain.keyName }}</div>-->
                <div style="margin-top: 2px">{{ formatDate(explain.valueDate) }}</div>
              </div>
            </div>
          </div>
          <div style="height: 470px;">
            <el-form
              label-width="80px"
              style="width: 100%;margin-top: 5px"
            >
              <el-form-item label="ID">
                <span>{{ explain.explainId }}</span>
              </el-form-item>
              <el-form-item :label="$t('keyName')">
                <span>{{ explain.keyName }}</span>
              </el-form-item>
              <el-form-item :label="$t('type')">
                <span>{{ formatExplainType(explain.type) }}</span>
              </el-form-item>
              <el-form-item :label="$t('model')">
                <span>{{ explain.model }}</span>
              </el-form-item>
              <el-form-item :label="$t('unit')">
                <span>{{ explain.unit }}</span>
              </el-form-item>
              <el-form-item :label="$t('grade')">
                <span>{{ explain.grade }}</span>
              </el-form-item>
              <el-form-item :label="$t('frequency')">
                <span>{{ formatterSeconds(explain.updateFrequency) }}</span>
              </el-form-item>
              <el-form-item :label="$t('device')+$t('linkage')">
                <el-switch
                  v-model="explain.canDeviceLinkage"
                  :disabled="true"
                />
              </el-form-item>
              <el-form-item :label="$t('filter')+$t('repeat')">
                <el-switch
                  v-model="explain.filterRepeat"
                  :disabled="true"
                />
              </el-form-item>
              <el-form-item :label="$t('tag')">
                <el-tag
                  v-for="tag in explainTagList"
                  :key="tag"
                  class="mr-1"
                  closable
                  @close="deleteTagDeviceExplain(tag)"
                >
                  {{ tag.name }}
                </el-tag>
                <el-select v-if="showTagSelect" v-model="tagId" @change="tagSelect">
                  <el-option
                    v-for="item in tagList"
                    :key="item.tagId"
                    :label="item.name"
                    :value="item.tagId"
                  />
                </el-select>
                <el-button v-else type="text" icon="el-icon-plus" @click="showTagSelect = true" />
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card class="box-card" style="height: 623px">
          <el-tabs v-model="activeName">
            <el-tab-pane v-if="explain.type !== 'static' && explain.type !== 'static:multi'" :label="$t('history')" name="first">
              <el-date-picker
                v-model="startDate"
                type="datetime"
                :placeholder="$t('startDate')"
                align="right"
                :picker-options="pickerOptions1"
                value-format="timestamp"
                style=";margin-right: 5px"
              />
              <el-date-picker
                v-model="endDate"
                type="datetime"
                :placeholder="$t('endDate')"
                align="right"
                :picker-options="pickerOptions1"
                value-format="timestamp"
                style=";margin-right: 5px"
              />
              <el-button type="primary" icon="el-icon-search" @click="listSearch">{{ $t('search') }}</el-button>
              <div v-if="explain.type === 'line'" style="width: 100%;height:450px">
                <line-chart :chart-data="chartData" height="450px" />
              </div>
              <multi-line-chart
                v-else-if="explain.type === 'line:multi'"
                style="height: 450px;width: 100%;"
                :chart-data="chartData"
              />
              <el-table
                v-else
                :data="dataList"
                style="width: 100%"
                height="350"
              >
                <el-table-column :label="$t('value')" prop="val" />
                <el-table-column :label="$t('time')">
                  <template slot-scope="scope">
                    <i class="el-icon-time" />
                    <span style="margin-left: 13px">{{ formatDate(scope.row.createdTime) }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane
              v-if="explain.type !== 'string' && explain.type !== 'string:multi'"
              :label="$t('data')+$t('count')"
              name="second"
              style="height: 420px"
            >
              <el-form label-width="80px">
                <el-form-item :label="$t('wave')">
                  <el-input :value="wave + explain.unit" />
                </el-form-item>
                <el-form-item :label="$t('last')+$t('value')">
                  <el-input :value="explain.lastValue + explain.unit" />
                </el-form-item>
                <el-form-item :label="$t('value')">
                  <el-input :value="explain.value + explain.unit" />
                </el-form-item>
                <el-form-item :label="$t('min')+$t('value')">
                  <el-input :value="explain.minVal + explain.unit" />
                </el-form-item>
                <el-form-item :label="$t('max')+$t('value')">
                  <el-input :value="explain.maxVal + explain.unit" />
                </el-form-item>
                <el-form-item :label="$t('extremum')">
                  <el-input :value="extremum + explain.unit" />
                </el-form-item>
                <el-form-item :label="$t('count')">
                  <el-input :value="explain.count + explain.unit" />
                </el-form-item>
                <el-form-item :label="$t('number')">
                  <el-input :value="explain.num" />
                </el-form-item>
                <el-form-item :label="$t('average')+$t('value')">
                  <el-input :value="averageVal + explain.unit" />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane :label="$t('warn')+$t('config')" name="config">
              <div class="uni-scroll" style="height: 480px">
                <device-explain-config-warn :explain-id="explain.explainId" />
              </div>
            </el-tab-pane>
            <el-tab-pane :label="$t('device')+$t('warn')" name="warn">
              <div class="uni-scroll" style="height: 480px">
                <device-warn
                  :device-id="explain.deviceId"
                  :port="explain.port"
                  :key-name="explain.keyName"
                  :status="null"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import DeviceWarn from '@/components/DeviceWarn/index'
import DeviceExplainConfigWarn from '@/components/DeviceExplainConfigWarn/index'
import {
  formatDate,
  failureNotice,
  formatExplainType,
  successNotice
} from '@/util/common'
import {
  listData
} from '@/api/iot/iotDeviceExplainDataApi'
import {
  listTagDeviceExplainTagByUser,
  deleteTagDeviceExplain,
  insertTagDeviceExplain
} from '@/api/iot/iotTagDeviceExplainApi'
import { listTag } from '@/api/iot/iotTagApi'
import LineChart from '@/components/Chart/LineChart'
import {
  getEnableEval,
  getFilterRepeat
} from '@/util/storage'
import MultiLineChart from '@/components/Chart/MultiLineChart'

export default {
  name: 'DeviceExplainInfo',
  components: {
    DeviceWarn,
    LineChart, MultiLineChart,
    DeviceExplainConfigWarn
  },
  props: {
    explain: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      wave: '',
      extremum: '',
      averageVal: '',
      showTagSelect: false,
      enableEval: getEnableEval(),
      filterRepeat: getFilterRepeat(),
      chartData: null,
      tagList: [],
      tagId: null,
      explainTagList: [],
      dataList: [],
      activeName: 'first',
      startDate: null,
      endDate: null,
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },
  watch: {
    explain: {
      deep: true,
      handler(val) {
        if (val != null) {
          this.init()
        }
      }
    }
  },
  created() {
    const timestamp = new Date().getTime() + 5 * 60 * 60 * 1000
    this.startDate = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
    this.endDate = timestamp
    this.listTag()
    this.init()
  }, methods: {
    init() {
      this.wave = ''
      this.extremum = ''
      this.averageVal = ''
      if (this.explain.type === 'line:multi' || this.explain.type === 'static:multi') {
        const valueList = this.explain.value.split(',')
        const lastValueList = this.explain.lastValue.split(',')
        const maxValList = this.explain.maxVal.split(',')
        const minValList = this.explain.minVal.split(',')
        const countList = this.explain.count.split(',')
        for (let i = 0, j = valueList.length; i < j; i++) {
          if (this.wave !== '') {
            this.wave = this.wave + ','
          }
          this.wave = this.wave + (parseFloat(valueList[i]) - parseFloat(lastValueList[i]))
        }
        for (let i = 0, j = maxValList.length; i < j; i++) {
          if (this.extremum !== '') {
            this.extremum = this.extremum + ','
          }
          this.extremum = this.extremum + (parseFloat(maxValList[i]) - parseFloat(minValList[i]))
        }
        for (let i = 0, j = countList.length; i < j; i++) {
          if (this.averageVal !== '') {
            this.averageVal = this.averageVal + ','
          }
          this.averageVal = this.averageVal + (parseFloat(countList[i]) / this.explain.num)
        }
      } else if (this.explain.type === 'line' || this.explain.type === 'static') {
        this.wave = (parseFloat(this.explain.value) - parseFloat(this.explain.lastValue))
        this.extremum = this.explain.maxVal - this.explain.minVal
        this.averageVal = this.explain.count / this.explain.num
      }
      this.listData()
    },
    tagSelect() {
      insertTagDeviceExplain({
        tagId: this.tagId,
        explainId: this.explain.explainId
      }).then(res => {
        const { code } = res
        if (code === '200') {
          this.listTagDeviceExplainTagByUser()
          this.showTagSelect = false
        }
      })
    },
    listTag() {
      listTag({}).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.tagList = data
        } else {
          this.tagList = []
        }
      })
    },
    deleteTagDeviceExplain(tag) {
      deleteTagDeviceExplain({
        id: tag.id
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listTagDeviceExplainTagByUser()
      })
    },
    listTagDeviceExplainTagByUser() {
      listTagDeviceExplainTagByUser({
        explainId: this.explain.explainId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.explainTagList = data
        } else {
          this.explainTagList = []
        }
      })
    },
    formatterSeconds(time) {
      if (time > 60) {
        return parseInt(time / 60) + this.$t('minutes')
      } else {
        return time + this.$t('seconds')
      }
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    formatExplainType(type) {
      return formatExplainType(this, type)
    },
    listSearch() {
      if (this.startDate == null) {
        failureNotice(this, this.$t('start') + this.$t('time'))
        return
      }
      if (this.endDate == null) {
        failureNotice(this, this.$t('end') + this.$t('time'))
        return
      }
      this.listData()
    },
    listData() {
      this.listTagDeviceExplainTagByUser()
      if (this.explain.type === 'static') {
        this.activeName = 'config'
        return
      }
      listData({
        port: this.explain.port,
        deviceId: this.explain.deviceId,
        startTime: Math.round(this.startDate / 1000),
        endTime: Math.round(this.endDate / 1000),
        keyName: this.explain.keyName,
        enableEval: this.enableEval === '1',
        filterRepeat: this.filterRepeat === '1'
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          if (this.explain.type === 'line') {
            const dy = []
            const dx = []
            for (const item of data) {
              dx.push(formatDate(this, item.createdTime))
              dy.push(item.val)
            }
            this.chartData = {
              ...this.explain,
              dataList: dy,
              dateList: dx
            }
          } else if (this.explain.type === 'line:multi') {
            const xList = []
            const yList = []
            for (const item of data) {
              xList.push(formatDate(this, item.createdTime))
              const valList = item.val.split(',')
              for (let n = 0, m = valList.length; n < m; n++) {
                const yd = valList[n]
                let have = false
                for (const yItem of yList) {
                  if (yItem.name === n) {
                    yItem.dataList.push(yd)
                    have = true
                    break
                  }
                }
                if (!have) {
                  yList.push({
                    name: n,
                    unit: this.explain.unit,
                    dataList: [yd]
                  })
                }
              }
            }
            this.chartData = {
              ...this.explain,
              dateList: xList,
              dataList: yList
            }
          } else {
            this.dataList = data
          }
        }
      })
    }
  }
}
</script>

